package admin

import (
	"errors"
	"fmt"

	"qkleague/db"
	"qkleague/errorcode"

	"time"

	"doubimeizhi.com/datatable"
	"doubimeizhi.com/utility"
	log "github.com/cihub/seelog"
)

func (p *adminService) ListWashRoom(req *ShowItemReq, resp *ShowItemResp, leagueId, washroomName, washRoomId string, id int) error {
	log.Debug("ListWashRoom, leagueId, washroomName, washRoomId", leagueId, washroomName, washRoomId)
	dtq := p.washRoomDtq(leagueId, washroomName, washRoomId, id)
	sql, val := dtq.GenerateSQL()
	log.Debugf("sql:%s, val:%v", sql, val)
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, val...)
	if err == nil {
		if len(results) == 0 {
			log.Warnf("查询没有包含此类信息的洗衣点，ListWashRoom, leagueId:%s, washroomName:%s, washRoomId:%s", leagueId, washroomName, washRoomId)
		}
		for _, dt := range results {
			li := p.washRoomParseRecords(mysqlHelper, dt)
			resp.Data = append(resp.Data, li)
		}
	} else {
		log.Errorf("mysql err sql:%s, err:%s", sql, err.Error())
	}

	if !req.Role {
		s, v := dtq.GenerateTotalRecordSQL("total_records")
		if results, err := mysqlHelper.Query(s, v...); err == nil {
			if len(results) > 0 {
				resp.Total = mysqlHelper.GetColInt(results[0], "total_records")
			}
		} else {
			log.Errorf("mysql err sql:%s, values:%v", err.Error(), v)
		}
	}
	if resp.Total > resp.PageSize {
		resp.HasMore = true
	}
	resp.Code = errorcode.EC_GL_SUCCESS
	resp.Msg = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	resp.PageIndex = req.PageIndex
	return nil
}

func (p *adminService) GetSomeWashRoom(leagueId, washRoomId string, id int) (error, []*QKLWashRoom) {
	resp := make([]*QKLWashRoom, 0)
	dtq := p.washRoomDtq(leagueId, "", washRoomId, id)
	sql, val := dtq.GenerateSQL()
	log.Debugf("mysql:%s, val:%v", sql, val)
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, val...)
	if err == nil {
		if len(results) == 0 {
			log.Warnf("查询没有包含此类信息的洗衣点，ListWashRoom, leagueId:%s, washRoomId:%s", leagueId, washRoomId)
			return errors.New("查询没有包含此类信息的洗衣点"), nil
		}
		for _, dt := range results {
			resp = append(resp, p.washRoomParseRecords(mysqlHelper, dt))
		}
		return nil, resp
	} else {
		log.Errorf("mysql err sql:%s, err:%s", sql, err.Error())
	}
	return errors.New("数据库查询失败"), nil
}

func getWasherNumByWashRoomId(washRoomId string) int {
	sql := "select count(distinct washer_id) as nums from washer_info"
	sql = fmt.Sprintf("%s where room_id = '%s'", sql, washRoomId)
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	if results, err := mysqlHelper.Query(sql); err == nil {
		return mysqlHelper.GetColInt(results[0], "nums")
	} else {
		log.Errorf("getWasherNumByWashRoomId err, err:%s, washroom_id:%s", err.Error(), washRoomId)
	}
	return 0
}

func getLeagueInfoByWashRoomId(leagueId string) *QKLeague {
	if err, info := GetAdminService().GetSomeLeague(5, leagueId); err == nil && len(info) != 0 {
		return info[0]
	}
	return nil
}

func (p *adminService) washRoomDtq(leagueId, washroomName, washRoomId string, id int) *datatable.DataTableQuery {
	dtq := datatable.NewDataTableQuery()
	dtq.SetTableName("wash_room")
	dtq.PushField(&datatable.FiledItem{Alias: "id", Field: "id"})
	dtq.PushField(&datatable.FiledItem{Alias: "room_id", Field: "room_id"})
	dtq.PushField(&datatable.FiledItem{Alias: "userid", Field: "userid"})
	dtq.PushField(&datatable.FiledItem{Alias: "name", Field: "name"})
	dtq.PushField(&datatable.FiledItem{Alias: "lat", Field: "lat"})
	dtq.PushField(&datatable.FiledItem{Alias: "lng", Field: "lng"})
	dtq.PushField(&datatable.FiledItem{Alias: "area", Field: "area"})
	dtq.PushField(&datatable.FiledItem{Alias: "addr_detail", Field: "addr_detail"})
	dtq.PushField(&datatable.FiledItem{Alias: "region_code", Field: "region_code"})
	dtq.PushField(&datatable.FiledItem{Alias: "deploy_type", Field: "deploy_type"})
	dtq.PushField(&datatable.FiledItem{Alias: "is_test", Field: "is_test"})
	dtq.PushField(&datatable.FiledItem{Alias: "type", Field: "type"})
	dtq.PushField(&datatable.FiledItem{Alias: "insert_tick", Field: "insert_tick"})

	if leagueId != "" {
		dtq.PushCondition("userid=?", leagueId)
	}
	if washRoomId != "" {
		dtq.PushCondition("room_id=?", washRoomId)
	}

	if washroomName != "" {
		dtq.PushCondition("name=?", washroomName)
	}
	if id > 0 {
		dtq.PushCondition("id=?", id)
	}
	return dtq
}

func (p *adminService) washRoomParseRecords(mysqlHelper *utility.MySQLHelper, dt map[string]interface{}) *QKLWashRoom {
	li := &QKLWashRoom{}
	li.Id = mysqlHelper.GetColInt64(dt, "id")
	li.WashRoomId = mysqlHelper.GetColString(dt, "room_id")
	li.LeagueId = mysqlHelper.GetColString(dt, "userid")
	li.WashRoomName = mysqlHelper.GetColString(dt, "name")
	li.Lat = mysqlHelper.GetColString(dt, "lat")
	li.Lng = mysqlHelper.GetColString(dt, "lng")
	li.Area = mysqlHelper.GetColString(dt, "area")
	li.AddrDetail = mysqlHelper.GetColString(dt, "addr_detail")
	li.RegionCode = mysqlHelper.GetColString(dt, "region_code")
	li.DeployType = mysqlHelper.GetColInt(dt, "deploy_type")
	li.IsTest = mysqlHelper.GetColInt(dt, "is_test")
	li.Type = mysqlHelper.GetColInt(dt, "type")
	insertTick := mysqlHelper.GetColInt64(dt, "insert_tick")
	tm := time.Unix(insertTick, 0)
	li.InsertTime = tm.Format("2006-01-02 15:04:05")
	li.WasherNum = getWasherNumByWashRoomId(li.WashRoomId)

	linfo := getLeagueInfoByWashRoomId(li.LeagueId)
	if linfo != nil {
		li.LeagueName = linfo.NickName + "(" + linfo.Mobile + ")"
		li.LeagueId = linfo.LeagueId
	} else {
		li.LeagueName = li.LeagueId
		li.LeagueId = li.LeagueId
	}

	return li
}
